﻿using AutoMapper;
using FarmSmartSleep.Common.Domain;
using FarmSmartSleep.Common.Domain.BeginTable;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using System.Reflection;

namespace FarmSmartSleep.Organ.API.Application.SleepInfoCommands.RecordCommands
{
    public class SheepInforHandler : IRequestHandler<SheepInforCommand, Result>
    {
        public readonly IBaseRepository<SleepInfor> sleepInforRepository;
        private readonly IMapper mapper;

        public SheepInforHandler(IBaseRepository<SleepInfor> sleepInforRepository, IMapper mapper)
        {
            this.sleepInforRepository = sleepInforRepository;
            this.mapper = mapper;
        }
        //羊只档案添加
        public async Task<Result> Handle(SheepInforCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.add };
            SleepInfor sleepInfor = mapper.Map<SleepInfor>(request);
            //查询该耳号的数量，如果结果大于1 说明有重复
            var res=sleepInforRepository.GetAll().Where(x=>x.EarNumber == request.EarNumber).Count();
            if (res>=1)
            {
                result.Messege = "该耳号已存在";
                result.Code = -1;
                return result;
            }
            else
            {
                var list = sleepInforRepository.Add(sleepInfor);
                result.Code = list;
            }


            return result;
        }
    }
}
